package com.fingersoft.feature.lock

import android.app.Activity
import android.content.Context
import android.graphics.Color
import androidx.annotation.Nullable
import android.text.TextUtils
import android.util.Log
import android.widget.Toast
import cn.fingersoft.util.BuildConfigUtil
import com.fingersoft.badger.AppBadgerManager
import com.fingersoft.business.BusinessContext
import com.fingersoft.business.bambooCloud.IBambooCloudProvider
import com.fingersoft.business.bambooCloud.IEPassAuthCallback
import com.fingersoft.business.deviceverify.VerifyDeviceEntity
import com.fingersoft.business.user.UserInfoCreator
import com.fingersoft.common.ICallback
import com.fingersoft.common.preference.UserAppPreferenceHelper
import com.fingersoft.common.preference.provider.UserIdProvider
import com.fingersoft.dexload.DexLoadUtil
import com.fingersoft.feature.faceId.FaceIDExport
import com.fingersoft.feature.login.*
import com.fingersoft.feature.login.api.LoginDataUser
import com.fingersoft.feature.login.api.LoginParam
import com.fingersoft.feature.newlock.ILockCallBack
import com.fingersoft.feature.newlock.LockManager
import com.fingersoft.feature.newlock.LockManager.Companion.LOCK_SUCCESS_PIN_MATCH
import com.fingersoft.feature.newlock.LockManager.Companion.LOCK_TYPE_GESTURE
import com.fingersoft.feature.newlock.LockMode
import com.fingersoft.feature.newlock.LoginData
import com.fingersoft.feature.personal.api.ApiUtils
import com.fingersoft.feature.personal.api.SetPasswordResponse2
import com.fingersoft.feature.personal.ui.FindBackPasswordActivity
import com.fingersoft.feature.userinfo.model.User
import com.fingersoft.feature.webview.WebViewManager
import com.fingersoft.im.R
import com.fingersoft.im.api.UserAgent
import com.fingersoft.im.api.base.BaseModelCallback2
import com.fingersoft.im.api.base.BaseResponse2
import com.fingersoft.im.api.model.UserInfo
import com.fingersoft.im.base.MyActivityManager
import com.fingersoft.im.event.EventManager
import com.fingersoft.im.ui.home.startMainActivity
import com.fingersoft.im.utils.*
import com.fingersoft.im.view.LoadDialog
import com.fingersoft.theme.ThemeM
import com.fingersoft.util.AppEventType
import com.fingersoft.util.AppEventUtil
import com.google.gson.Gson
import com.loopj.android.http.AsyncHttpClient
import com.loopj.android.http.AsyncHttpResponseHandler
import com.loopj.android.http.RequestParams
import com.lzy.okgo.OkGo
import okhttp3.Call
import okhttp3.Response
import org.apache.http.Header
import org.greenrobot.eventbus.EventBus
import java.io.File
import java.lang.ref.WeakReference
import java.util.*
import kotlin.collections.HashMap

class SealLockCallBackImpl(private val context: Context) : ILockCallBack {
    override fun setGesturePassword(context: Context, password: String?) {
        ApiUtils.setGesturePassWord(context, password, ICallback<Any>(Any::class.java))
    }

    override fun isLogged(): Boolean {
        return AppUtils.isLogged()
    }

    override fun getLogin_module(context: Context): String {
        return AppConfigUtils.getAppConfigInfo(context).login_module ?: ""
    }

    override fun  usFaceLogin(context: Context):Boolean{
        return AppConfigUtils.getAppConfigInfo(context).isFace_login
    }

    override fun showLoginUername(context: Context):Boolean {
        return getUnlockPageProperty(context) == "username"
    }

    fun getUnlockPageProperty(context: Context):String{//解锁页面 显示 账号 or 姓名;"username#账号", "name#姓名"
        return AppConfigUtils.getAppConfigInfo(context).unlock_page_property
    }

    override fun setFaceRecognitionSwitchOn(isop: Boolean) {
        FaceIDExport.setFaceIdSwitchStatus(isop)
    }

    override fun getFace_user_permission(context: Context?, url: String, callBack: ICallback<Any>) {
        OkGo.post(AppUtils.getApiUrl(url, AppUtils.J_ECODE))
            .headers("Emp-Info", JSONUtils.toJsonString(UserAgent(context, AppUtils.getTokenInfo().userToken, AppUtils.getTokenInfo().did)))
            //.upJson(params)
            .execute(object : BaseModelCallback2<SetPasswordResponse2>(SetPasswordResponse2::class.java) {
                override fun onSuccess(setPasswordResponse2: SetPasswordResponse2, call: Call, response: Response) {
                    super.onSuccess(setPasswordResponse2, call, response)
                    callBack.onSuccess(setPasswordResponse2.code)
                }

                override fun onError(call: Call?, response: Response?, e: Exception?) {
                    super.onError(call, response, e)
                    callBack.onError()
                }

            })
    }

    override fun logoutAndGoSecondLoginPage(context: Context) {
        AppEventUtil.writeLandingState(AppEventType.AppLogout)
        getUserAppPreferenceHelper().putBoolean("isJustLogout", true)
        val user:User = AppUtils.getUser()
        LockManager.instance.init(context, user.getPassword(), user.getEmpLivingPhoto(), user.getRealName(),user.getGender(), user.jobNnumber);
        LockManager.instance.doLoginOut()
        val userInfo:UserInfo = UserInfoManager.getCurrentUserInfo()
        LockManager.loginUserAvatar= userInfo.icon
        LockManager.loginUserName=userInfo.name
        AppUtils.logout(context)
    }

    override fun doFaceRecognition(context: Context) {
        FaceIDExport.startLiveRecognition(context)
        //FaceIDExport.startPhotoRecognition(context)
    }

    override fun doFaceLogin(context: Context) {
        FaceIDExport.startFaceLogin(context)
    }

    override fun isFaceRecognitionEnable(): Boolean {
        return FaceIDExport.isModuleEnable()
    }

    override fun isFaceRecognitionSwitchOn(): Boolean {
        return FaceIDExport.isSwitchOn()
    }

    fun createUserData(data: com.fingersoft.feature.login.api.LoginData?): LoginData? {
        if (data == null) {
            return null
        }
        val loginData = LoginData()
        loginData.deviceId = data.deviceId
        loginData.secondCheck = data.secondCheck
        loginData.usertoken = data.usertoken
        loginData.user = createLoginDataUser(data.user)
        return loginData
    }

    private fun createLoginDataUser(user: LoginDataUser?): com.fingersoft.feature.newlock.LoginDataUser? {
        if (user == null) {
            return null
        }
        val loginDataUser = com.fingersoft.feature.newlock.LoginDataUser()
        loginDataUser.cellPhone = user.cellPhone
        loginDataUser.id = user.id
        loginDataUser.duty = user.duty
        loginDataUser.usertoken = user.deptId
        loginDataUser.deptId = user.deptId
        loginDataUser.phone = user.phone
        loginDataUser.mobile = user.mobile
        loginDataUser.icon = user.icon
        loginDataUser.imid = user.imid
        loginDataUser.name = user.name
        loginDataUser.deptName = user.deptName
        loginDataUser.dutyName = user.dutyName
        loginDataUser.gender = user.gender
        loginDataUser.genderMemo = user.genderMemo
        loginDataUser.gesturePassword = user.gesturePassword
        loginDataUser.username = user.username
        loginDataUser.password = user.password
        loginDataUser.additional = com.fingersoft.feature.newlock.LoginDataUser.Additional()
        return loginDataUser
    }

    fun handleLogin(context: Activity?,password: String?,loginData: com.fingersoft.feature.login.api.LoginData?,callback: ICallback<LoginData>){
        if(loginData == null){
            return
        }
        var data = loginData
        if (data.hideBadge == true) {
            AppBadgerManager(context!!).hide()
        } else {
            AppBadgerManager(context!!).show()
        }
        data.user!!.username = AppUtils.getUser().userName
        data.user!!.password = password
        data.deviceId = LoginContext.instance!!.deviceId
        LoginContext.instance!!.saveCurrentUserInfo(context, data)
        BusinessContext.user!!.onLogin(context, UserInfoCreator.create(data)!!)
        callback.onSuccess(createUserData(data))
        if (data.secondCheck!!) {
            LoginContext.instance!!.onSecondCheck(context, data, object : ISecondCheckCallback {
                override fun onSuccess() {
                    requestForRongCloud(context, data)
                }

                override fun onError() {
                    LoadDialog.dismiss(context)
                }
            })
            return
        }
        requestForRongCloud(context, data)
    }

    fun handleLogin(context:Activity?,password:String,loginResponse2: SealLoginContext.LoginResponse2?,
                    callback: ICallback<LoginData>){
        if (AppUtils.showApiSucceedErrorToast(loginResponse2)) {
            callback.onError()
            return
        }
        var data = loginResponse2?.data!!
        handleLogin(context,password,data,callback)
    }
    override fun doFaceLogin(context: Activity?, faceImgPath: String, callback: ICallback<LoginData>) {
        val requestParams = RequestParams()
        requestParams.put("username", AppUtils.getUser().userName)
        requestParams.put("file", File(faceImgPath))
        val asyncHttpClient = AsyncHttpClient()
        val url = AppUtils.getApiUrl("am/sec/auth/face", AppUtils.J_ECODE)
        asyncHttpClient.addHeader("Emp-Info",AppUtils.makeAppAgentInfo(context))
        asyncHttpClient.post(url, requestParams,
            object : AsyncHttpResponseHandler() {
                override fun onSuccess(i: Int, headers: Array<Header>, bytes: ByteArray) {
                    val successStr = String(bytes)
                    //ToastUtils.show("doFaceLogin successStr:"+successStr, Toast.LENGTH_LONG);
                    try {//
                        val loginResponse2: SealLoginContext.LoginResponse2 = Gson().fromJson(successStr,SealLoginContext.LoginResponse2::class.java)
                        handleLogin(context,"",loginResponse2,callback)
                    } catch (e1: Exception) {
                        e1.printStackTrace()
                        callback.onError()
                    }
                }
                override fun onFailure(statusCode: Int, headers: Array<Header>?,
                                       responseBody: ByteArray?, throwable: Throwable?) {
                    callback.onError()
                }

            })
    }
    var mBambooCloudProvider: IBambooCloudProvider? = BusinessContext.mBambooCloudProvider
    val useBambooCloud:Boolean = BuildConfigUtil.getBoolean("useBambooCloud")
    fun doPwdLoginReq(context: Activity?, username: String, password: String, pwdAsUsername: Boolean, loginType: String, callback: ICallback<LoginData>) {
        val param = LoginParam()
        if (pwdAsUsername) {
            param.username = AppUtils.getUser().userName
            if (loginType == "thirdToken") {
                param.username = password
            }
        } else {
            param.username = username
        }
        param.password = password
        param.loginType = loginType
        APIUtils2().login(WeakReference<Activity>(context),param.username,param.password,loginType,
            object : ICallback<com.fingersoft.feature.login.api.LoginData>(){
            override fun onSuccess(data: com.fingersoft.feature.login.api.LoginData?) {
                handleLogin(context, "", data, callback)
            }

            override fun onError() {
                callback.onError()
            }
        })
    }

    override fun doLogin(context: Activity?, password: String, loginType: String, callback: ICallback<LoginData>, username: String) {
        val userName = if(username.isNullOrEmpty()) AppUtils.getUser().userName else username
        mBambooCloudProvider = BusinessContext.mBambooCloudProvider
        if(useBambooCloud && mBambooCloudProvider != null){
            mBambooCloudProvider?.authByPwd(context!!, userName, password,
                object : IEPassAuthCallback() {
                    override fun success(deviceID: String, encryptString: String) {
                        doPwdLoginReq(context,userName, encryptString,true,"zhuyunSDK", callback)
                    }

                    override fun error(msg: String?) {
                        LoadDialog.dismiss(context)
                        ToastUtils.showWithoutDelay(String.format(context.getString(R.string.login_bamboo_login_failure), msg ?: ""))
                    }
                })
        } else if(loginType.equals("thirdToken")) {//第三方token登录
            doPwdLoginReq(context,password, password,true,"thirdToken", callback)
        } else {
            doPwdLoginReq(context,userName, password,true,"usernamePwd", callback)
        }
    }

    override fun doBambooCloudSmsLogin(context: Activity?, mobile:String,verCode: String, callback: ICallback<LoginData>){
        val userName = AppUtils.getUser().userName
        mBambooCloudProvider = BusinessContext.mBambooCloudProvider
        mBambooCloudProvider?.authBySms(context!!, mobile, verCode,
            object : IEPassAuthCallback() {
                override fun success(deviceID: String, encryptString: String) {
                    doPwdLoginReq(context,userName, encryptString,true,"zhuyunSDK",  callback)
                }

                override fun error(msg: String?) {
                    LoadDialog.dismiss(context)
                    ToastUtils.showWithoutDelay(String.format(context.getString(R.string.login_bamboo_login_failure), msg ?: ""))
                }
            })
    }

    override fun getSolidUserForLogin(contextWeakReference: WeakReference<Context>): VerifyDeviceEntity? {
        val verifyEntity = BusinessContext.deviceVerify?.getDeviceVerification(contextWeakReference)
        return if (BuildConfigUtil.getBoolean("useVerifyDevicePolicy", false)) {
            verifyEntity
        } else {
            null
        }
    }

    override fun doLoginWithPhoneCode(context: Activity?, identityCode: String, loginMode: String, callback: ICallback<LoginData>) {
        val param = LoginParam()
        param.username = AppUtils.getUser().mobile
        param.password = identityCode
        param.loginType = loginMode
        OkGo.post(AppUtils.getApiUrl("am/sec/auth", AppUtils.J_ECODE))
            .upJson(JSONUtils.toJsonString(param))
            .execute<SealLoginContext.LoginResponse2>(object : BaseModelCallback2<SealLoginContext.LoginResponse2>(SealLoginContext.LoginResponse2::class.java) {
                override fun onSuccess(loginResponse2: SealLoginContext.LoginResponse2, call: Call, response: Response) {
                    super.onSuccess(loginResponse2, call, response)
                    if (AppUtils.showApiSucceedErrorToast(loginResponse2)) {
                        callback.onError()
                        return
                    }
                    val data = loginResponse2.data!!
                    data.deviceId = LoginContext.instance!!.deviceId
                    LoginContext.instance!!.saveCurrentUserInfo(context, data)
                    BusinessContext.user!!.onLogin(context!!, UserInfoCreator.create(data)!!)
                    callback.onSuccess(createUserData(loginResponse2.data))
                    if (data.secondCheck!!) {
                        LoginContext.instance!!.onSecondCheck(context, loginResponse2.data, object : ISecondCheckCallback {
                            override fun onSuccess() {
                                requestForRongCloud(context, loginResponse2.data!!)
                            }

                            override fun onError() {
                                LoadDialog.dismiss(context)
                            }
                        })
                        return
                    }
                    requestForRongCloud(context, data)
                }

                fun createUserData(data: com.fingersoft.feature.login.api.LoginData?): LoginData? {
                    if (data == null) {
                        return null
                    }
                    val loginData = LoginData()
                    loginData.deviceId = data.deviceId
                    loginData.secondCheck = data.secondCheck
                    loginData.usertoken = data.usertoken
                    loginData.user = createLoginDataUser(data.user)
                    return loginData
                }

                private fun createLoginDataUser(user: LoginDataUser?): com.fingersoft.feature.newlock.LoginDataUser? {
                    if (user == null) {
                        return null
                    }
                    val loginDataUser = com.fingersoft.feature.newlock.LoginDataUser()
                    loginDataUser.cellPhone = user.cellPhone
                    loginDataUser.id = user.id
                    loginDataUser.duty = user.duty
                    loginDataUser.usertoken = user.deptId
                    loginDataUser.deptId = user.deptId
                    loginDataUser.phone = user.phone
                    loginDataUser.mobile = user.mobile
                    loginDataUser.icon = user.icon
                    loginDataUser.imid = user.imid
                    loginDataUser.name = user.name
                    loginDataUser.deptName = user.deptName
                    loginDataUser.dutyName = user.dutyName
                    loginDataUser.gender = user.gender
                    loginDataUser.genderMemo = user.genderMemo
                    loginDataUser.gesturePassword = user.gesturePassword
                    loginDataUser.username = user.username
                    loginDataUser.password = user.password
                    loginDataUser.additional = com.fingersoft.feature.newlock.LoginDataUser.Additional()
                    return loginDataUser
                }

                override fun onError(call: Call?, response: Response?, e: Exception?) {
                    super.onError(call, response, e)
                    callback.onError()
                }
            })
    }

    override fun doLoginWithThirdToken(context: Activity?, identityCode: String, thirdToken: String, callback: ICallback<LoginData>) {
        doPwdLoginReq(context, identityCode, thirdToken, false,"thirdToken", callback)
    }

    override fun sendCode(context: Activity?, callback: ICallback<Any>) {
        val mobile = AppUtils.getUser().mobile
        if (mobile == null || mobile.trim({ it <= ' ' }).isEmpty()) {
            ToastUtils.show("手机号码不得为空")
            return
        }
        if (!mobile.matches("[1][345678]\\d{9}".toRegex())) {
            ToastUtils.show("手机号码不正确")
            return
        }
        LoadDialog.show(context, "获取中")
        val params = HashMap<String, String>()
        params["mobile"] = mobile
        val gson = Gson()
        val jsonStr = gson.toJson(params)
        OkGo.post(AppUtils.getApiUrl("am/sec/sendCode", AppUtils.J_ECODE))
            .upJson(jsonStr)
            .execute<SealLoginContext.LoginResponse2>(object : BaseModelCallback2<SealLoginContext.LoginResponse2>(SealLoginContext.LoginResponse2::class.java) {
                override fun onSuccess(loginResponse2: SealLoginContext.LoginResponse2, call: Call, response: Response) {
                    super.onSuccess(loginResponse2, call, response)
                    if (AppUtils.showApiSucceedErrorToast(loginResponse2)) {
                        callback.onError()
                        return
                    }
                    callback.onSuccess(loginResponse2.data!!)
                }

                override fun onError(call: Call?, response: Response?, e: Exception?) {
                    super.onError(call, response, e)
                    callback.onError()
                }

            })
    }

    private fun requestForRongCloud(context: Activity, data: com.fingersoft.feature.login.api.LoginData) {
        LoginContext.instance!!.onLogin(context, data, object : ILoginCallback {
            override fun onSuccess() {
                afterLogin(context)
            }

            override fun onError() {
                LoadDialog.dismiss(context)
                Toast.makeText(context, context!!.getString(R.string.login_rong_connect_failure), Toast.LENGTH_SHORT).show()
            }
        })
    }

    private fun afterLogin(context: Activity?) {
        LoadDialog.dismiss(context)
        LoginContext.instance!!.gotoMainActivity(context)
    }

    override fun getUserAccount(): String {
        return AppUtils.getUser().userName
    }
    override fun getNickname(): String {
        return AppUtils.getUser().realName
    }
    @Nullable
    override fun getUserMobile(): String {
        return if (null == AppUtils.getUser().mobile) "" else AppUtils.getUser().mobile
    }

    override fun getPhoneCode(path: String, json: String, callback: ICallback<BaseResponse2<String>>) {
        OkGo.post(AppUtils.getApiUrl(path, AppUtils.J_ECODE))
            .upJson(json)
            .execute(object : BaseModelCallback2<BaseResponse2<String>>(BaseResponse2::class.java) {
                override fun onSuccess(modelResponse: BaseResponse2<String>?, call: Call?, response: Response?) {
                    super.onSuccess(modelResponse, call, response)
                    if (path.contains("am/sec/sendCode")) {
                        if (null == modelResponse || 403 == modelResponse.getCode() || null == modelResponse.getData()) {
                            callback.onError(if (null == modelResponse) null else modelResponse.getMsg())
                            return
                        }
                    }
                    if (AppUtils.showApiSucceedErrorToast(modelResponse)) {
                        callback.onError()
                        return
                    }
                    callback.onSuccess(modelResponse)
                }

                override fun onError(call: Call?, response: Response?, e: java.lang.Exception?) {
                    super.onError(call, response, e)
                    AppUtils.showApiErrorToast()
                    callback.onError()
                }
            })

    }

    override fun getUserIcon(): String {
        return AppUtils.getUser().empLivingPhoto
    }

    override fun useTheme(): Boolean {
        return AppUtils.useTheme()
    }

    override fun getThemeColor(): Int {
        return ThemeM.themeColor
    }

    override fun getJ_Code(): String {
        return AppUtils.J_ECODE
    }

    override fun gotoFindBackPasswordActivity(context: Context) {
        val fpUrl = AppConfigUtils.getAppConfigInfo(context).forget_password_url
        if (!TextUtils.isEmpty(fpUrl)) {
            WebViewManager.openWebView(context, fpUrl, context.getString(R.string.forgot_password))
        } else {
            FindBackPasswordActivity.startFindBackPasswordActivity(context)
        }
    }

    /* 修改设置以及sp中手势密码的状态 */
    override fun changeGesture() {
        LockManager.instance.setPassword(LOCK_TYPE_GESTURE, AppUtils.getUser().gesturePassword)
    }


    override fun onModuleCreate(context: Context) {
        val user = AppUtils.getUser()
        LockManager.instance.init(context, user.password, user.empLivingPhoto, user.realName, user.gender, user.jobNnumber)
    }

    override fun onModuleDestory(context: Context?) {
//        LockManager.instance.finishView()
        context?.let { LockManager.instance.deinit(it) }
//        doFinish()
    }

    override fun onModuleViewDestory(context: Context?) {
        LockManager.instance.finishView()
//        doFinish()
    }

    override fun doFingerprintAuthenticate() {
        LockManager.instance.doFingerprintAuthenticate()
    }

    override fun doFingerPrintCheck(): Boolean {
        return LockManager.instance.checkFingerprint()
    }

    override fun onUnLockSuccess(context: Context?, suc: Int) {
        Log.e("lock", "success$suc")
        when (suc) {
            LockManager.LOCK_SUCCESS_PASSWORD_MATCH -> {
                EventBus.getDefault().post(EventManager.OnUnLockSuccess(suc))

            }
            LockManager.LOCK_SUCCESS_GESTURE_RESET -> {
                EventBus.getDefault().post(EventManager.OnSettingGesturePasswordPassed())
            }
            LockManager.LOCK_SUCCESS_GESTURE_SET -> {
                EventBus.getDefault().post(EventManager.OnSettingGesturePasswordPassed())
            }
            LockManager.LOCK_SUCCESS_GESTURE_SET_WITHJUMP -> {
                getUserAppPreferenceHelper().putString("isFirstSetGesture", "1")
                LockManager.instance.setEnable(LOCK_TYPE_GESTURE, true)
                EventBus.getDefault().post(EventManager.OnSettingGesturePasswordPassed())
            }
            LockManager.LOCK_GESTURE_DEL_SUCCESS -> {
                EventBus.getDefault().post(EventManager.OnSettingGesturePasswordPassed())
            }
            LockManager.FINGERPRINT_ENABLE -> {
                EventBus.getDefault().post(EventManager.OnSettingFingerPrintEable())
            }
            LockManager.LOCK_SUCCESS_FINGERPRINT_MATCH -> {
                EventBus.getDefault().post(EventManager.OnSettingFingerPrintPassed())
                EventBus.getDefault().post(EventManager.OnUnLockSuccess(suc))
            }
            LockManager.LOCK_SUCCESS_GESTURE_MATCH -> {
                EventBus.getDefault().post(EventManager.OnUnLockSuccess(suc))
            }
            LockManager.LOCK_SUCCESS_FACEID_MATCH, LOCK_SUCCESS_PIN_MATCH -> {
                EventBus.getDefault().post(EventManager.OnUnLockSuccess(suc))
            }
        }

        onModuleViewDestory(context)
    }

    /**
     *  登陆成功
     *  @param mode 解锁/登录，登录需要跳转到主界面
     *  */
    override fun onUnLockSuccess(context: Context, suc: Int, mode: LockMode) {
        onUnLockSuccess(context, suc)
        if (mode == LockMode.LOGIN) {
            startMainActivity(context, 0, false)
        }
    }

    override fun onUnLockFail(context: Context?, err: Int) {
        Log.e("lock", "err$err")
        when (err) {
            LockManager.LOCK_ERR_FACE_INCORRECT -> {
                ToastUtils.show("人脸错误")
            }

            LockManager.LOCK_ERR_PASSWORD_INCORRECT -> {
                ToastUtils.show("密码错误")
            }

            LockManager.LOCK_ERR_PHONECODE_INCORRECT -> {
                ToastUtils.show("验证码错误")
            }

            LockManager.LOCK_ERR_PASSWORD_EMPTY -> {
                ToastUtils.show("密码不能为空")
            }

            LockManager.LOCK_ERR_PHONECODE_EMPTY -> {
                ToastUtils.show("验证码不能为空")
            }

            LockManager.LOCK_ERR_GESTURE_INCORRECT -> {
                EventBus.getDefault().post(EventManager.OnUnLockFail(err))
            }
            LockManager.LOCK_ERR_FINGERPRINT_MATCH_FAIL -> {
                EventBus.getDefault().post(EventManager.OnUnLockFail(err))
            }
            LockManager.FINGERPRINT_SDK_VERSION_ERR -> {
                EventBus.getDefault().post(EventManager.OnSettingFingerPrintDisable())
            }
            LockManager.FINGERPRINT_NOT_SET_ERR -> {
                EventBus.getDefault().post(EventManager.OnSettingHasNoFingerPrint())
            }
            LockManager.FINGERPRINT_NOT_SET_LOCK_ERR -> {
                EventBus.getDefault().post(EventManager.OnSettingHasNoLockPassword())
            }
            LockManager.LOCK_ERR_GESTURE_OUT_LIMIT -> {
                EventBus.getDefault().post(EventManager.OnGesturePasswordMatchOutLimit())
            }
            LockManager.LOCK_ERR_FACEID_MATCH_FAIL -> {
                //ToastUtils.show("刷脸解锁失败")
                EventBus.getDefault().post(EventManager.OnUnLockFail(err))
            }
        }
    }

    override fun onUserChange(context: Activity?, res: Int) {
        Log.e("lock", "res$res")
        when (res) {
            LockManager.LOCK_TYPE_CHANGE_USER -> {
                AppUtils.logout(context)
                LoginActivity.start(context)//跳转到第一次登录页
                LockManager.instance.finishView()
            }
        }
    }

    override fun onJunpOverSetGesture(context: Context?, res: Int) {
        Log.e("lock", "res$res")
        getUserAppPreferenceHelper().putString("isFirstSetGesture", "1")
        changeGesture()
    }

    override fun getUserAppPreferenceHelper(): UserAppPreferenceHelper {
        return UserAppPreferenceHelper(object : UserIdProvider() {
            override fun getUserId(): String {
                return AppUtils.getUser().userId ?: ""
            }
        })
    }


    override fun doFinish() {
        LockManager.instance.finishView()
        val activityList = MyActivityManager.getInstance().activityList
        for (activity in activityList) {
            if (activity != null) {
                activity.finish()
            }
        }
    }

    override fun getConfig(context: Context): Boolean {
        return AppConfigUtils.getAppConfigInfo(context).isForget_password
    }

    override fun loginBackgroundIsFull(): Boolean {
        return AppUtils.loginBackgroundIsFull()
    }

    override fun loginFontStyleIsDark(): Boolean {
        return AppUtils.loginFontStyleIsDark()
    }

    override fun loginButtonColor(): String {
        return AppUtils.loginButtonColor()
    }

    override fun loginButtonTextColor(): Int {
        return Color.parseColor(AppUtils.loginButtonTextColor())
    }
}
